#pragma once

#include <tchar.h>
#include <dshow.h>
#include <atlbase.h>
#include <qedit.h>
#include <set>
namespace avlib{

#define WM_GRAPHNOTIFY  WM_APP+1

#define SAFE_RELEASE(x) { if (x) x.Release(); x = NULL; }


class AviFile;
class VideoRecorder{

private:

	CComPtr<ICaptureGraphBuilder2> m_pBuilder;
	CComPtr<IGraphBuilder>	m_pGraph;
	
	//capture filter
	CComPtr<IBaseFilter>	m_pCapture;

	//sample grabber
	CComPtr<ISampleGrabber> m_pGrabber;

	//control interface
	CComPtr<IVideoWindow> m_pVideoWindow;
	CComPtr<IMediaControl> m_pMediaControl;
	CComPtr<IMediaEventEx> m_pMediaEvent;
	CComPtr<IMediaSeeking> m_pMediaSeeking;
	CComPtr<IBasicAudio> m_pBasicAudio;

	
	HWND  m_wndPreview;
	
	
	//get the capture filter from index(start from 1);
	HRESULT GetCaptureFilter(int idx,IBaseFilter ** filter);
	
	HRESULT SetCaptureSize(IBaseFilter *pCapture);
	HRESULT EnumCaptureCapability();
	

	//CRITICAL_SECTION cs;

	bool init_bmp(int w,int h);


	int m_fps;
	void *m_pBits;

	unsigned m_timer;

	int m_width,m_height;
	int buff_sz;
	
	AviFile *m_avi;
public:

	VideoRecorder();
	~VideoRecorder();
	bool  init();
	bool open(int idx,HWND preview);

	bool start(AviFile *avi);
	bool stop();

	void blt();
	void close();

	void *get_bits();
	void release_bits();

	void set_capture_size(int w,int h){
		m_width = w;
		m_height = h;
	}

	void set_fps(int fps){
		m_fps = fps;
	}

	//HIWORD as width,LOWORD as height
	bool query_supported_dimension(int idx,std::set<DWORD> & dimensions);
	HRESULT SetupVideoWindow(HWND hWnd);
		

};
};